package com.lamda.zhekou.master;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
 
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        /**
         * Creates a new instance firing {@link IdleStateEvent}s.
         *
         * @param readerIdleTime
         *        an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
         *        will be triggered when no read was performed for the specified
         *        period of time.  Specify {@code 0} to disable.
         * @param writerIdleTime
         *        an {@link IdleSta teEvent} whose state is {@link IdleState#WRITER_IDLE}
         *        will be triggered when no write was performed for the specified
         *        period of time.  Specify {@code 0} to disable.
         * @param allIdleTime
         *        an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
         *        will be triggered when neither read nor write was performed for
         *        the specified period of time.  Specify {@code 0} to disable.
         * @param unit
         *        the {@link TimeUnit} of {@code readerIdleTime},
         *        {@code writeIdleTime}, and {@code allIdleTime}
         */
        pipeline.addLast("ping", new IdleStateHandler(0, 0, 30,  TimeUnit.SECONDS));
//        pipeline.addLast("ping", new IdleStateHandler(60, 15, 3,  TimeUnit.SECONDS));
        // 以("\n")为结尾分割的 解码器
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                Delimiters.lineDelimiter()));
        // 字符串解码 和 编码
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        // 自己的逻辑Handler
        pipeline.addLast("handler", new ServerHandler());
    }
}